#include "MTPK53_002NGF06.h"
#include <stdlib.h>

const struct TouchPoint keyCenterPosition[] = 
{
    {43, 382},
    {42, 521},
    {231, 455},
    {240, 596},
    {433, 381},
    {423, 520},
};

uint8_t TouchState;

extern uint8_t tpInt;
extern uint8_t is_power_down;

int getKey()
{
	uint16_t x, y;
    struct TouchPoint point;
	uint8_t buf[4];
	while (1) {
		//MOD
		//if (is_power_down == 0 /*&& ST_INT == 0*/) {
		if (is_power_down == 0 && tpInt == 1 ) {
			ST1633_RD_Reg(0x12, buf, 20);
            printf("\r\n");

			for(uint8_t i = 0; i < 5; i++) {
				if(buf[i*4] & 0x80)
				{
					point.x = (uint16_t)((buf[i*4] & 0x70) << 4 | buf[i*4+1]);
					point.y = (uint16_t)((buf[i*4] & 0x07) << 8 | buf[i*4+2]);
                    printf(" touch %d: X=%d,Y=%d\r\n",i, point.x, point.y);

                    for(uint8_t j = 0; j< 6; j++)
                    {
                        if(pointIsInsideSquare(point, keyCenterPosition[j], TOUCHKEY_RADIUS))
                        {
                            printf("key %d is touched!\r\n", j);
                        }
                    }

					
				}
				else
				{
					//printf("point %d not valid\r\n", i);
				}
			}
			tpInt = 0;
		}
		
		delay_ms(20);
	}
}

void mtpTouchKeyTest(void)
{
	printf("Enter ST1633 test cases\r\n");

	int result = 0;
	result = ST1633_Init();
	printf(" initial result: =%d\r\n", result);

	getKey();
}

uint8_t pointIsInsideSquare(struct TouchPoint pointToTest, struct TouchPoint squareCenter, uint16_t squareHalfWidth)
{
    return ( abs(pointToTest.x - squareCenter.x) <= squareHalfWidth && abs(pointToTest.y - squareCenter.y) <= squareHalfWidth );
}
